import { createRouter, createWebHistory } from 'vue-router';
import AppLayout from '../layouts/AppLayout.vue';
import Home from '../views/Home.vue';
import FileManager from '../views/FileManager.vue';
import ResultCenter from '../views/ResultCenter.vue';
import WorkflowDesigner from '../views/WorkflowDesigner.vue';
import LLMAssitant from '../views/LLMAssitant.vue';
import UserLogin from '@/components/user/UserLogin.vue';
import UserRegister from '@/components/user/UserRegister.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: AppLayout,
      children: [
        {
          path: '',
          name: 'home',
          component: Home,
          meta: {
            requiresAuth: true,
          },
        },
        {
          path: 'file-manager',
          name: 'file-manager',
          component: FileManager,
          meta: {
            requiresAuth: true,
          },
        },
        {
          path: 'result-center',
          name: 'result-center',
          component: ResultCenter,
          meta: {
            requiresAuth: true,
          },
        },
        {
          path: 'workflow-designer',
          name: 'workflow-designer',
          component: WorkflowDesigner,
          meta: {
            requiresAuth: true,
          },
        },
        {
          path: 'llm-assistant',
          name: 'llm-assistant',
          component: LLMAssitant,
          meta: {
            requiresAuth: true,
          },
        }
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: UserLogin,
    },
    {
      path: '/register',
      name: 'register',
      component: UserRegister,
    },
  ],
});

router.beforeEach(async (to, from, next) => {
  if(to.meta.requiresAuth) {
    const token = !!localStorage.getItem('token');

    if(!token) {
      next({name: 'login'})
      return;
    } else {
      next()
    }
  } else {
    next()
  }
});

export default router;
